clear;

load('CM_factors.mat');

Models = {{'3'},{'3','2'},{'3','2','5'},{'3','2','5','1'},{'3','2','5','1','4'}};

JumpIndicator = true;

mean_est = [];
std_est = [];

% Convert the last set of models into numeric indices and use them to get row names
if ~JumpIndicator

    rowNames = factors_name(str2double(Models{length(Models)}));

    rowNames = {rowNames{[1:end]},'R2'};

else

    rowNames = factors_name(str2double(Models{length(Models)}));
    rowNames = reshape([rowNames; strcat(rowNames, ' Jumps')], 1, []);
    rowNames = {rowNames{[1:end]},'R2'};


end

% Determine the number of models
numModels = length(Models);

% Create a square table of empty strings with correct dimensions
emptyData = repmat({''}, length(rowNames), numModels*2);

% Generate variable names based on the number of models

% Generate model names
modelNames = arrayfun(@(x) sprintf('Model%d', x), 1:numModels, 'UniformOutput', false);

% Create an array with interleaved empty strings
varNames = cell(1, 2*numModels);
varNames(1:2:end) = modelNames;
varNames(2:2:end) = strcat(modelNames, ' tStat');

% Display variable names
%disp(varNames);


% Create the table
T = array2table(emptyData, 'RowNames', rowNames, 'VariableNames', varNames);

for model    = length(Models):-1:1  


    if ~JumpIndicator
        
        load(['CM_Model_',num2str(model),'.mat'], 'Lambda_hat_AJX', 'Vn_AJX','R2_t');
        T.(['Model',num2str(model)])(1:length(Lambda_hat_AJX)) = arrayfun(@(x) sprintf('$%.2f$', x),round(100*Lambda_hat_AJX',2), 'UniformOutput', false);
        T.(['Model',num2str(model),' tStat'])(1:length(Lambda_hat_AJX)) = arrayfun(@(x) sprintf('$(%.2f)$', x),round(Lambda_hat_AJX'./sqrt(diag(Vn_AJX)),2), 'UniformOutput', false);
        T.(['Model',num2str(model)])(length(rowNames)) =  arrayfun(@(x) sprintf('$%.2f$', x),round(100*mean(R2_t),2), 'UniformOutput', false);

    else

        load(['CM_J_Model_',num2str(model),'.mat'], 'Lambda_hat_AJX', 'Vn_AJX','R2_t');
        T.(['Model',num2str(model)])(1:length(Lambda_hat_AJX)) = arrayfun(@(x) sprintf('$%.2f$', x),round(100*Lambda_hat_AJX',2), 'UniformOutput', false);    
        T.(['Model',num2str(model),' tStat'])(1:length(Lambda_hat_AJX)) = arrayfun(@(x) sprintf('$(%.2f)$', x),round(Lambda_hat_AJX'./sqrt(diag(Vn_AJX)),2), 'UniformOutput', false);
        T.(['Model',num2str(model)])(length(rowNames)) =  arrayfun(@(x) sprintf('$%.2f$', x),round(100*mean(R2_t),2), 'UniformOutput', false);

    end

end


writetable(T, ['CM_Results.csv']);


